<template>
<div v-loading="loading">
  <el-form
    ref="RunReviewRef"
    :model="formData"
    :rules="rules"
    :size="size"
    status-icon
    label-width="100px"
  >
    <el-row>
      <!-- 知识编号 -->
      <el-col :span="7">
        <el-form-item prop="code" label="知识编号：">
          <el-input v-model="formData.code" autocomplete="off" disabled/>
        </el-form-item>
      </el-col>

      <!-- 审核组 -->
      <el-col :span="7">
        <el-form-item prop="reviewGroupId" label="审核组：">
          <el-select
            v-model="formData.reviewGroupId"
            placeholder="请选择审核组"
            style="width: 240px"
            @change="handleGroupChange"
           disabled >
            <el-option
              v-for="item in props.reviewData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <!-- 审核成员 -->
      <el-col :span="7">
        <el-form-item prop="reviewerList" label="审核成员：">
          <el-select
            v-model="formData.reviewerList"
            multiple
            filterable
            
            placeholder="请选择审核成员"
            style="width: 240px"
            disabled >
            <el-option
              v-for="user in filteredReviewerData(formData.reviewGroupId)"
              :key="user.userId"
              :label="user.personname"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 审核结果 -->
    <el-row>
      <el-col :span="24">
        <el-form-item label="审核结果" prop="reviewStatus">
          <el-radio-group v-model="formData.reviewStatus">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="3">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="7">  
          <el-form-item  class="form-item" prop="reviewEndTime" label="审核时间：" label-width="80px">
            <el-date-picker
              v-model="formData.reviewEndTime"
              type="datetime"
              placeholder="选择日期时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :clearable="true"
            />
          </el-form-item>
        </el-col>
    </el-row>

    <!-- 驳回时显示 -->
    <el-row v-if="formData.reviewStatus === 3">
      <el-col :span="24">
        <el-form-item label="修改建议：" prop="rejectReason">
          <el-input
            type="textarea"
            v-model="formData.rejectReason"
            placeholder="请输入修改建议"
            :rows="3"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 通过时显示 -->
    <el-row v-if="formData.reviewStatus === 2">
      <el-col :span="24">
        <el-form-item label="审核意见：" prop="approveReason">
          <el-input
            type="textarea"
            v-model="formData.approveReason"
            placeholder="请输入审核意见"
            :rows="3"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 底部按钮 -->
    <div class="dialog-footer">
      <el-button @click="resetForm">清空</el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </div>
  </el-form>
  </div>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits, nextTick, onMounted, onBeforeMount, reactive} from 'vue'
import _ from 'lodash'
import {getKnowledgeReviewRecordsInfoHandler} from "../../api/knowledge.js"
const emit = defineEmits(['update:reviewRecordsData', 'RunReviewSubmit'])

const props = defineProps({
  reviewRecordsData: { type: Object, required: true },
  departmentdata: Array,
  typeData: Array,
  userinfo: Array,
  reviewData: Array
})
const loading = ref(false)
const RunReviewRef = ref(null)
const size = ref('small')

// 深拷贝 props，避免父子相互影响
// 表单数据
const formData = reactive({
    id: null,
    code: "",
    reviewGroupId: null,
    reviewerList: [],
    reviewerId: null,
    reviewTime: null,
    reviewEndTime: null,
    rejectReason: "",
    approveReason: "",
    reviewStatus: null,
})

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入知识编号', trigger: 'blur' }],
  reviewGroupId: [{ required: true, message: '请选择审核组', trigger: 'change' }],
  reviewerList: [{ required: true, message: '请选择审核成员', trigger: 'change' }],
  reviewStatus: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  reviewEndTime: [{ required: true, message: '请选择审核时间', trigger: 'change' }],
  rejectReason: [
    {
      required: true,
      message: '请输入修改建议',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (formData.reviewStatus === 3 && !value) {
          callback(new Error('驳回时必须填写修改建议'))
        } else {
          callback()
        }
      }
    }
  ],
  approveReason: [
    {
      required: true,
      message: '请输入审核意见',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (formData.reviewStatus === 2 && !value) {
          callback(new Error('通过时必须填写审核意见'))
        } else {
          callback()
        }
      }
    }
  ]
}

let initialized = false

// ✅ 监听 props.reviewRecordsData 变化后再加载接口数据
watch(
  () => props.reviewRecordsData,
  async (newVal) => {
    if (!newVal || !newVal.code) return
    loading.value = true
    try {
        // 先清空旧数据，避免上次内容残留
        Object.keys(formData).forEach(k => formData[k] = "")
        // 调接口加载当前数据
        const res = await getKnowledgeReviewRecordsInfoHandler(newVal.code, newVal.reviewStatus)
        const queryData = res?.data?.data?.queryData || {}

        // await nextTick()    

        for (const key in formData) {
        formData[key] = queryData[0][key] ?? ""
        }
    } catch (error) {
      console.error("❌ 查询审核中数据失败:", error)
    } finally {
      loading.value = false
      initialized = true
    }
  },
  { immediate: true, deep: true }
)

// ✅ 双向同步 formData → 父组件
watch(
  formData,
  (val) => {
    if (!initialized) return
    emit('update:reviewRecordsData', _.cloneDeep(val))
  },
  { deep: true }
)

// ✅ 监听审核状态切换（保持逻辑不变）
watch(
  () => formData.reviewStatus,
  (newVal) => {
    if (!initialized) return
    if (newVal === 2) formData.rejectReason = ''
    if (newVal === 3) formData.approveReason = ''
  }
)

// ---------- 逻辑方法 ----------
const handleGroupChange = () => {
  formData.reviewerList = []
}

const filteredReviewerData = (groupId) => {
  if (!groupId) return []
  const group = props.reviewData?.find((g) => g.id === groupId)
  return group?.users ?? []
}

const resetForm = () => {
  if (RunReviewRef.value) RunReviewRef.value.resetFields()
  Object.assign(formData, props.reviewRecordsData)
}
const getReviewerId=()=>{
    const loginName = localStorage.getItem('loginName')
    console.log('登录名:', loginName)
    console.log("用户信息", props.userinfo)
    const reviewerid=props.userinfo.find(item=>item.username=loginName)?.id
    console.log("用户id", reviewerid)
    return reviewerid
}
const submitForm = async () => {
  if (!RunReviewRef.value) return
  await RunReviewRef.value.validate((valid) => {
    if (valid) {
      const reviewerid=getReviewerId()
      formData.reviewerId=reviewerid
      console.log('提交成功:', formData)
      emit('RunReviewSubmit', _.cloneDeep(formData))
    } else {
      console.warn('表单验证失败')
    }
  })
}
</script>

<style scoped>
.form-item {
  width: 300px;
  margin: 10px auto;
}
.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style>